package com.vrv.vap.uploader.service;

import com.vrv.vap.uploader.config.UploadConfig;
import com.vrv.vap.uploader.mapper.FileMapper;
import com.vrv.vap.uploader.model.FileDto;
import com.vrv.vap.uploader.utils.FileUtils;
import com.vrv.vap.uploader.utils.UploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

/**
 * 文件上传服务
 */
@Service
public class FileService {

    @Autowired
    private FileMapper fileMapper;

    public Boolean deleteById(Long id) {
        int i = fileMapper.deleteById(id);
        return i > 0 ;
    }

    /**
     * 上传文件
     * @param md5
     * @param file
     */
    public void upload(String name,
                       String md5,
                       MultipartFile file) throws IOException {
        String path = UploadConfig.path + FileUtils.generateFileName();
        FileUtils.write(path, file.getInputStream());
        fileMapper.save(new FileDto(name, md5, path, new Date(), FileUtils.getExt(file)));
    }

    /**
     * 分块上传文件
     * @param md5
     * @param size
     * @param chunks
     * @param chunk
     * @param file
     * @throws IOException
     */
    public void uploadWithBlock(String name,
                                String md5,
                                Long size,
                                Integer chunks,
                                Integer chunk,
                                MultipartFile file) throws IOException {
        String fileName = UploadUtils.getFileName(md5, chunks);
        FileUtils.writeWithBlok(UploadConfig.path + fileName, size, file.getInputStream(), file.getSize(), chunks, chunk);
        UploadUtils.addChunk(md5,chunk);
        if (UploadUtils.isUploaded(md5)) {
            UploadUtils.removeKey(md5);
            fileMapper.save(new FileDto(name, md5,UploadConfig.path + fileName, new Date(), FileUtils.getExt(file)));
        }
    }

    /**
     * 检查Md5判断文件是否已上传
     * true:  未上传
     * false: 已上传
     * @param md5
     * @return
     */
    public boolean checkMd5(String md5) {
        FileDto fileDTO = new FileDto();
        fileDTO.setMd5(md5);
        return fileMapper.getByFile(fileDTO) == null;
    }


    public FileDto queryFileById(Long id){
        FileDto fileDto = fileMapper.getById(id);
        return fileDto;
    }

    public boolean update( FileDto fileDto){
        int update = fileMapper.update(fileDto);
        return update > 0;
    }
}
